package org.jeecg.modules.rental.service.impl;


import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.rental.entity.RentalStore;
import org.jeecg.modules.rental.entity.TransferRecord;
import org.jeecg.modules.rental.mapper.RentalStoreMapper;
import org.jeecg.modules.rental.mapper.TransferRecordMapper;
import org.jeecg.modules.rental.service.ITransferRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 调车记录表
 * @Author: jeecg-boot
 * @Date:   2025-02-26
 * @Version: V1.0
 */
@Service
public class TransferRecordServiceImpl extends ServiceImpl<TransferRecordMapper, TransferRecord> implements ITransferRecordService {


    @Autowired
    private RentalStoreMapper rentalStoreMapper; // 网点表的 Mapper
    @Override
    public List<Map<String, Object>> getTransferRecordList(String storeName, String startDate, String endDate, String status) {
        QueryWrapper<TransferRecord> queryWrapper = new QueryWrapper<>();

        // 按条件查询
        if (storeName != null && !storeName.isEmpty()) {
            queryWrapper.like("store_name", storeName);
        }
        if (startDate != null && !startDate.isEmpty()) {
            queryWrapper.ge("apply_time", startDate);
        }
        if (endDate != null && !endDate.isEmpty()) {
            queryWrapper.le("apply_time", endDate);
        }
        if (status != null && !status.isEmpty()) {
            queryWrapper.eq("status", status);
        }

        queryWrapper.orderByDesc("apply_time"); // 按申请时间倒序
        return this.baseMapper.selectMaps(queryWrapper);
    }

    @Override
    public void applyTransfer(Long storeId, String useTime, Integer num) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(useTime, formatter);

        // 获取网点信息
        RentalStore store = rentalStoreMapper.selectById(storeId);
        if (store == null) {
            throw new RuntimeException("网点不存在");
        }

        // 创建调车记录
        TransferRecord record = new TransferRecord();
        record.setStoreId(storeId);
        record.setStoreName(store.getMeshPointsName());
        record.setUseTime(dateTime); // 转换日期
        record.setNum(num);
        record.setStatus(0); // 默认状态为调车中
        record.setApplyTime(new Date());
        this.save(record);
    }
}
